<!-- ----------------------------
--  @author: 野狼上校           --
--  @create: 2024-03-23 15:45  --
--  @version: 1.0              --
-------------------------------->
<!-- 用户相关的数据展示及操作（如CRUD、授权，等等） -->

<template>
  <el-breadcrumb :separator-icon="DArrowRight" style='font: normal bold 1.1rem "Fira Sans", serif;'>
    <el-breadcrumb-item v-for="(item, index) in items" :key="index">{{ item }}</el-breadcrumb-item>
  </el-breadcrumb>
  <el-divider/>
  <!--  查询条件  -->
  <el-row :gutter="20" class="my-query">
    <el-col :span="6">
    </el-col>
    <el-col :span="8">
      <el-input placeholder="请输入账号或手机号码" v-model="queryForm.username" clearable/>
    </el-col>
    <el-col :span="4">
      <el-button type="primary" :icon="Search" @click="initUsersData">查询</el-button>
    </el-col>
    <el-col :span="6">
    </el-col>
  </el-row>

  <!-- 列表数据 -->
  <el-row :gutter="20" class="my-table">
    <el-col :span="4">
      用户列表
    </el-col>
    <el-col :span="16">
    </el-col>
    <el-col :span="4">
      <el-button type="success" :icon="Plus" @click="addUserHandler">新增</el-button>
    </el-col>
  </el-row>

  <!--  表格数据  -->
  <el-table :data="users" stripe border style="width: 100%">
    <el-table-column prop="username" label="账号" width="100" align="center"/>
    <el-table-column prop="phone" label="手机号码" width="120" align="center"/>
    <el-table-column prop="roles" label="拥有角色" width="200" align="center">
      <template #default="{row}">
        <el-tag size="small" type="warning" v-for="role in row.roles">
          {{ role.roleNameZh }}
        </el-tag>
      </template>
    </el-table-column>

    <el-table-column prop="companyName" label="所属公司" width="120" align="center"/>

    <el-table-column prop="accountNonExpired" label="账号过期" width="120" align="center">
      <template #default="{row}">
        {{ false === row.accountNonExpired ? '否' : '是' }}
      </template>
    </el-table-column>

    <el-table-column prop="accountNonLocked" label="账号锁定" width="120" align="center">
      <template #default="{row}">
        {{ false === row.accountNonLocked ? '否' : '是' }}
      </template>
    </el-table-column>

    <el-table-column prop="credentialsNonExpired" label="凭证过期" width="120" align="center">
      <template #default="{row}">
        {{ false === row.credentialsNonExpired ? '否' : '是' }}
      </template>
    </el-table-column>

    <el-table-column prop="enabled" label="状态" width="120" align="center">
      <template #default="{row}">
        <el-tooltip :content=" false === row.enabled ? '禁用' : '启用'" placement="right">
          <el-switch v-model="row.enabled"
                     :active-value="true"
                     :inactive-value="false"
                     @change="handleEnabledChange(row)"
          />
        </el-tooltip>
      </template>
    </el-table-column>
    <el-table-column prop="action" label="操作" min-width="300px" fixed="right" align="center">
      <template v-slot="scope">
        <!--     修改     -->
        <el-button type="primary" :icon="Edit" @click="editUserHandler(scope.row)"/>
        <!--     系统管理员信息不能被删除     -->
        <el-button type="primary" :icon="Delete" v-if="scope.row.username !== 'shangxiao'"
                   @click="deleteUserHandler(scope.$index,scope.row.id)"/>
      </template>
    </el-table-column>
  </el-table>

  <!--  分页插件  -->
  <el-pagination
      v-model:current-page="pagination.pageNum"
      v-model:page-size="pagination.pageSize"
      class="el-pagination"
      :page-sizes="[10, 20, 30, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />

  <!-- 新增 -->
  <AddUser v-model="dialogAddUserVisible" :dialogAddUserVisible="dialogAddUserVisible"
           @initUsersData="initUsersData"/>
  <!-- 修改 -->
  <EditUser v-model="dialogEditUserVisible" :dialogEditUserVisible="dialogEditUserVisible"
            :userRowInfo="userRowInfo" @initUsersData="initUsersData"/>
</template>

<script setup lang="ts">
import {useRoute} from "vue-router";
import {DArrowRight, Delete, Edit, Plus, Search} from "@element-plus/icons-vue";
import {onMounted, ref} from "vue";
import {Action, ElMessage, ElMessageBox} from "element-plus";
import {deleteUserById, getUsersByPage, patchUser} from "@/api/auth/user.ts";
import {SUCCESS} from "@/utils/constants.ts";
import AddUser from "@/views/system/user/add.vue";
import EditUser from "@/views/system/user/edit.vue";
import {RespResult} from "@/api";

const breadcrumb: any = useRoute().meta.title;
const items: string[] = breadcrumb.split(",");

/*查询条件*/
const queryForm = ref({
  username: ""
});

/*表格数据*/
const users = ref([]);

/*分页条件*/
const pagination = ref({
  pageNum: 1,
  pageSize: 10
})
/*总记录数*/
const total = ref(0);
/*改变每页显示数量*/
const handleSizeChange = (pageSize: number) => {
  pagination.value.pageNum = 1;
  pagination.value.pageSize = pageSize
  initUsersData();
}
/*改变页码*/
const handleCurrentChange = (pageNum: number) => {
  pagination.value.pageNum = pageNum;
  initUsersData();
}

/*初始化表格数据*/
onMounted(() => {
  initUsersData();
})
const initUsersData = async () => {
  //发送请求
  await getUsersByPage({
    pageSize: pagination.value.pageSize,
    pageNum: pagination.value.pageNum,
    username: queryForm.value.username
  }).then(
      (response: RespResult) => {
        if (response.code === SUCCESS) {
          const jsonObject = JSON.parse(response.data);
          users.value = jsonObject.records;
          total.value = jsonObject.total;
        } else {
          ElMessage({
            message: "获取数据失败",
            type: 'error'
          })
        }
      }
  )
}

/*新增*/
const dialogAddUserVisible = ref(false);
const addUserHandler = () => {
  //显示弹出框
  dialogAddUserVisible.value = true;
}

/*改变用户状态*/
const handleEnabledChange = async (row: any) => {
  await patchUser({
    id: row.id,
    enabled: row.enabled ? 1 : 0
  }).then(
      (response: RespResult) => {
        if (response.code === SUCCESS) {
          ElMessage({
            message: "操作成功",
            type: "success"
          })
        } else {
          ElMessage({
            message: response.message,
            type: "error"
          })
        }
      }
  )
}

/*修改*/
const dialogEditUserVisible = ref(false);
const userRowInfo = ref({})
const editUserHandler = (row: any) => {
  //显示弹出框
  dialogEditUserVisible.value = true;
  userRowInfo.value = row;
}


/*删除*/
const deleteUserHandler = (index: any, id: number) => {
  if (id === 1) {
    ElMessage({
      message: "系统管理员不能被删除",
      type: "warning"
    })
  } else {
    ElMessageBox.confirm(
        '你确定要删除吗?',
        '警告:',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    ).then(async () => {
      await deleteUserById(id).then(
          (response: RespResult) => {
            if (response.code === SUCCESS) {
              //从页面上删除记录
              users.value.splice(index, 1);
              initUsersData();
              ElMessage({
                message: "删除成功",
                type: "success"
              })
            } else {
              ElMessage({
                message: "删除失败",
                type: "error"
              })
            }
          }
      )
    }).catch((action: Action) => {
      console.log("取消或关闭" + action)
    })
  }
}
</script>

<style scoped>
.my-query {
  margin-left: 0 !important;
  margin-right: 0 !important;
  margin-bottom: 20px;
  padding-top: 15px;
  padding-bottom: 15px;
  border: 1px solid #DDDDDD;
  box-sizing: border-box;
}

.my-table {
  margin-left: 0 !important;
  margin-right: 0 !important;
  margin-bottom: 5px;
  padding-top: 15px;
  padding-bottom: 15px;
  border: 1px solid #DDDDDD;
  box-sizing: border-box;
}

.el-pagination {
  float: right;
  padding: 20px;
  box-sizing: border-box;
}

</style>